"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 夏令时跳转时备份
Create At   : 2020/11/27
@zou_jialiang0505328126
Description :
    1.设置夏令时，03/08/2020 01:59:55(3月份第二个周日，即将开始夏令时)
    2.主机执行备份指令
    3.使用备份文件恢复主机
    4.主备切换
Expect      :
    1.修改主机时间成功
    2.备份成功
    3.恢复成功
    4.主备切换成功
History     :
    Modified by @wan005 2021/3/23: 增加环境时区修复步骤
"""

import os
import unittest
import sys
import time
from yat.test import macro
from yat.test import Node
import datetime

sys.path.append(sys.path[0] + "/../")
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

# 默认  /etc/localtime -> ../usr/share/zoneinfo/Asia/Shanghai
New_York_Local = '/usr/share/zoneinfo/America/New_York'
LN_SF_CMD = 'ln -sf {zone} /etc/localtime'

class Basebackup(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    commonshsta = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Tools_Backup_Case006.py 开始执行------------')
        self.dbPrimaryDbUser = Node(node='PrimaryDbUser')
        self.dbStandby1DbUser = Node(node='Standby1DbUser')
        self.dbStandby2DbUser = Node(node='Standby2DbUser')
        self.dbStandby1Root = Node(node='Standby1Root')
        self.dbPrimaryRootNode = Node(node='PrimaryRoot')
        self.Constant = Constant()
        self.common = Common('PrimaryRoot')
        self.backup_file = os.path.join(macro.DB_BACKUP_PATH, 'backup_dir')
        self.primary_hostname = self.dbPrimaryRootNode.sh('hostname').result()
        self.currentLocalZoneStr = self.dbPrimaryRootNode.sh('ls -l /etc/localtime').result()
        self.log.info(f'before timezone is {self.currentLocalZoneStr}')

        result = self.common.check_system_timezone(
            *('PrimaryRoot', 'Standby1Root', 'Standby2Root'))
        self.log.info(result)
        self.assertTrue(result)

        self.log.info('-------------------创建备份路径-----------------------------------')
        shell_cmd = f'rm -rf {self.backup_file}; mkdir {self.backup_file};'
        self.log.info(shell_cmd)
        result = self.dbPrimaryDbUser.sh(shell_cmd).result()
        self.log.info(result)

    def test_backup(self):
        self.log.info("---------------1.设置夏令时，03/08/2020 01:59:55(3月份第二个周日，即将开始夏令时)：成功---------------------")
        self.log.info("============修改 postgresql.conf================")
        cmd = '''\
                    cp {dbIns}/postgresql.conf {dbIns}/postgresql.conf.timezone;
                    echo "timezone=America/New_York" >> {dbIns}/postgresql.conf
                '''.format(dbIns=macro.DB_INSTANCE_PATH)
        self.dbPrimaryDbUser.sh(cmd)

        self.log.info("==========重载配置文件=========")
        result = self.commonshpri.reloadDbConfig()
        self.log.info(result)
        self.assertIn(self.Constant.RELOAD_SUCCESS_MSG, result)

        self.log.info("=========设置主节点时区为纽约============")
        zonecmd = LN_SF_CMD.format(zone=New_York_Local)
        self.dbPrimaryRootNode.sh(zonecmd)
        self.log.info("设置操作系统时间为 03/08/2020 01:59:55(3月份第二个周日，即将开始夏令时)")
        datecmd = 'date -s \'03/08/2020 01:59:55\''
        self.dbPrimaryRootNode.sh(datecmd)
        beforeTime = self.commonshpri.executDbSql('select now();')
        self.log.info(beforeTime)
        self.assertIn("01:5", beforeTime)

        self.log.info('--------------------2.主机执行备份指令：成功----------------------------')
        result = self.commonshpri.execu_gs_backup('backup', self.primary_hostname, self.backup_file, "--all")
        self.assertIn(self.Constant.BACKUP_BACKUP_SUCCESS_MSG, result)
        time.sleep(3)
        cmd = f'ls -l {self.backup_file} |grep "^-"|wc -l'
        self.log.info(cmd)
        result = self.dbPrimaryDbUser.sh(cmd).result()
        self.log.info(result)
        self.assertLess(0, int(result))
        afterTime = self.commonshpri.executDbSql('select now();')
        self.log.info(afterTime)
        self.assertIn("2020-03-08 03", afterTime)

        self.log.info('-------------------3.使用备份文件恢复主机:成功-----------------------------------')
        result = self.commonshpri.execu_gs_backup('restore', self.primary_hostname, self.backup_file, "--all")
        self.assertIn(self.Constant.BACKUP_RESTORE_SUCCESS_MSG, result)

        self.log.info('-------------------4.主备切换------------------------')
        result = self.commonshsta.executeGsctl('switchover', self.Constant.SWITCH_SUCCESS_MSG)
        self.assertTrue(result)
        result = self.commonshsta.exec_refresh_conf()
        self.assertTrue(result)

    def tearDown(self):
        self.log.info('-------------------------环境清理------------------------')
        self.log.info('--------------------------删除备份文件------------------')
        shell_cmd = f'rm -rf {self.backup_file}'
        self.log.info(shell_cmd)
        result = self.dbPrimaryDbUser.sh(shell_cmd).result()
        self.log.info(result)
        result = self.dbStandby1DbUser.sh(shell_cmd).result()
        self.log.info(result)
        result = self.dbStandby2DbUser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('-------------------------恢复主备关系----------------------')
        result = self.commonshsta.check_whether_need_switch(self.primary_hostname)
        if result:
            result = self.commonshpri.executeGsctl('switchover', self.Constant.SWITCH_SUCCESS_MSG)
            self.log.info(result)
            result = self.commonshpri.exec_refresh_conf()
            self.log.info(result)

        self.log.info("-----------恢复系统时间--------------------")
        cmd = '''\
                       mv {dbIns}/postgresql.conf.timezone {dbIns}/postgresql.conf;
                   '''.format(dbIns=macro.DB_INSTANCE_PATH)
        self.dbPrimaryDbUser.sh(cmd)
        result = self.commonshpri.reloadDbConfig()
        self.log.info(result)

        result = self.dbPrimaryRootNode.sh('ls -l /etc/localtime').result()
        self.log.info(result)
        recoverTimezone = self.currentLocalZoneStr.split('->')[1]
        zonecmd = LN_SF_CMD.format(zone=recoverTimezone)
        self.log.info('recover: ' + zonecmd)
        self.dbPrimaryRootNode.sh(zonecmd)
        result = self.dbPrimaryRootNode.sh('ls -l /etc/localtime').result()
        self.log.info(result)

        currentTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        datecmd = 'date -s \'{}\''.format(currentTime)
        self.log.info('recover: ' + datecmd)
        self.dbPrimaryRootNode.sh(datecmd)
        self.log.info('----------Opengauss_Reliability_Tools_Backup_Case006.py 执行结束-----------------------')
